﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.IdentityModel.Logging;
using NetTaste;
using NPOI.SS.Formula.Functions;
using NPOI.XWPF.UserModel;
using SqlSugar.Extensions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace DFGK_WMS.Repository
{
    public class TTransferBinOrderRepository : BaseRepository<TTransferBinOrder>, ITTransferBinOrderRepository
    {
        public TTransferBinOrderRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        { 
        }

        /// <summary>
        /// 提交数据 （增加/修改/删除）
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool SubmitTransferBinOrderData(TTransferBinOrderDTO m)
        {
            //使用事务的原子性
            using (var trans = Context.Database.BeginTransaction())
            {
                try
                {
                    TTransferBinOrder tran = new TTransferBinOrder();
                    tran = Mapper.Map<TTransferBinOrder>(m);
                    bool isAdd = m.Id <= 0;
                    var com = Context.TCompanies.Where(c => c.Id == tran.CompanyId).FirstOrDefault();
                    #region 添加移库单
                    if (isAdd)
                    {
                        tran.CreateUserId = m.SubmitUserId;
                        tran.CreateUserName = m.SubmitUserName;
                        tran.CreateDate = DateTime.Now;
                        tran.ModifyDate = DateTime.Now;
                        tran.ModifyUserId = m.ModifyUserId;
                        tran.ModifyUserName = m.ModifyUserName;
                        tran.CompanyName = com.Name==null ? null : com.Name;
                        tran.Status = 0;
                    
                        Context.TTransferBinOrders.Add(tran);
                        Context.SaveChanges();
                        if (m.OrderDetailList != null && m.OrderDetailList.Count > 0)
                        {
                            foreach (var item in m.OrderDetailList)
                            {
                                item.OrderId = tran.Id;
                                item.OrderSn = tran.OrderSn;
                                item.CreateUserId = tran.CreateUserId;
                                item.CreateUserName = tran.CreateUserName;
                                item.CreateDate = tran.CreateDate;
                                item.ModifyUserId = tran.ModifyUserId;
                                item.ModifyUserName = tran.ModifyUserName;
                                item.ModifyDate = tran.ModifyDate;

                                #region 添加移库单明细
                                Context.TTransferBinOrderDetails.Add(item);
                                Context.SaveChanges();
                                
                                #endregion
                            }
                        }
                    }
                    #endregion

                    #region 修改/删除 移库单和移库单明细
                    else
                    {
                        #region 修改移库单
                        tran.ModifyDate = DateTime.Now;
                        tran.ModifyUserId = m.ModifyUserId;
                        tran.ModifyUserName = m.ModifyUserName;
                        tran.CompanyName = com.Name == null ? null : com.Name;
                        Context.TTransferBinOrders.Update(tran);
                        Context.SaveChanges();
                        #endregion

                        var listDetail = Context.TTransferBinOrderDetails.Where(t => t.OrderId == tran.Id).ToList();
                        if (listDetail != null && listDetail.Count > 0)
                        {
                            foreach (var item in listDetail)
                            {
                                Context.TTransferBinOrderDetails.Remove(item);
                            }
                            foreach (var item in m.OrderDetailList)
                            {
                                item.OrderId = tran.Id;
                                item.OrderSn = tran.OrderSn;
                                item.CreateUserId = tran.CreateUserId;
                                item.CreateUserName = tran.CreateUserName;
                                item.CreateDate = tran.CreateDate;
                                item.ModifyUserId = tran.ModifyUserId;
                                item.ModifyUserName = tran.ModifyUserName;
                                item.ModifyDate = tran.ModifyDate;

                                Context.TTransferBinOrderDetails.Add(item);
                                Context.SaveChanges();
                            }
                        }
                    }
                    #endregion
                    Context.SaveChanges();
                    //提交事务
                    trans.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    trans.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 删除移库单
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelTransferBinOrder(int tid)
        {
            var mobj = Context.TTransferBinOrders.Find(tid);
            if (mobj != null&&mobj.Status!=4)
            {

                Context.TTransferBinOrders.Remove(mobj);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 获取可用仓位
        /// </summary>
        /// <param name="fromLocationId"></param>
        /// <param name="isPriorityFilling"></param>
        /// <param name="filterType"></param>
        /// <param name="toLogicalPartCode"></param>
        /// <returns></returns>
        public List<TCell> GetEnabledCellListByFromLocationId(string? toLogicalPartCode,int FromLocationId, bool isPriorityFilling = false, int filterType = 1)
        {
            var cellQuery = Context.TCells.AsNoTracking().ToList();
            var shelfQuery = Context.TShelves;
            var inventoryQuery = Context.TInventories;
            var inventory = inventoryQuery.Where(i => i.LocationId == FromLocationId).FirstOrDefault();

            if (inventory is null)
            {
                return null;
            }
            if (inventory.IsMultPallet == true)
            {
                toLogicalPartCode = "MultPallet";//花盘定死
            }
            List<int?> list=null;
            if(isPriorityFilling)
            {
                if (filterType == 1)
                {
                    list = inventoryQuery.Where(i => i.MaterialId == inventory.MaterialId && i.MaterialKeyId == inventory.MaterialKeyId && i.Status == 1).Select(i => i.LocationId).ToList();
                }
                else if (filterType == 2)
                {
                    list = inventoryQuery.Where(i => i.MaterialId == inventory.MaterialId && i.Status == 1).Select(i => i.LocationId).ToList();
                }
                else
                {
                    list = inventoryQuery.Where(i => i.Status == 1).Select(i => i.LocationId).ToList();
                }
                cellQuery = cellQuery.Where(c => list.Contains(c.Id) && c.Status == (int)EmCellStatus.Normal && c.IsLock == false && c.BusinessType == 0 && c.FullStatus == 0 && c.HeightType >= inventory.RealHeightType && c.LayerNo == inventory.LocationLayerNo && c.LineNo == inventory.LocationLineNo && c.ColumnNo > inventory.LocationColumnNo && c.DepthIndex == inventory.LocationDepth).ToList();
            }
            else
            {
                cellQuery = cellQuery.Where(c => c.Status == (int)EmCellStatus.Normal && c.FullStatus == 0 && c.IsLock == false && c.BusinessType == 0 && c.HeightType >= inventory.RealHeightType).ToList();
            }
            if (!string.IsNullOrEmpty(toLogicalPartCode))
            {
                cellQuery = cellQuery.Where(t => t.LogicalPartCode == toLogicalPartCode).ToList();
            }
            return cellQuery.OrderBy(c=>c.HeightType)
                .ThenBy(c=>c.LineNo)
                .ThenBy(c=>c.DistanceValue)
                .ThenBy(c=>c.LayerNo)
                .ThenBy(c=>c.ColumnNo)
                .ThenBy(c=>c.DepthIndex)
                .ToList();
        }

        /// <summary>
        /// 查询单个移库信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TTransferBinOrder GetTransferBinOrderById(int id)
        {
            return Context.TTransferBinOrders.Find(id);
            //TTransferBinOrderDTO Tdto = new TTransferBinOrderDTO();
            //Tdto = Mapper.Map<TTransferBinOrderDTO>(tran);
            //Tdto.OrderDetailList = Context.TTransferBinOrderDetails.Where(t => t.OrderId == tran.Id).ToList();

        }

        /// <summary>
        /// 查询全部移库单信息
        /// </summary>
        /// <param name="kname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TransferSigles> GetTransferBinOrderList(string? ordersn, int? status, int issys, int pageIndex, int pageSize, out int totalCount)
        {
            List<TransferSigles> tlis = new List<TransferSigles>();
            var tranlist = Context.TTransferBinOrders.AsNoTracking();
            if(!string.IsNullOrEmpty(ordersn))
            {
                tranlist = tranlist.Where(x => x.OrderSn == ordersn);
            }
            if(status<8)
            {
                tranlist = tranlist.Where(x => x.Status == status);
            }
            if(issys!=0)
            {
                tranlist = tranlist.Where(x => x.OrderId !=null && x.OrderId.Length>0);
            }
            if(tranlist.Any())
            {
                foreach (var tOrder in tranlist)
                {
                    TransferSigles tranobj = new TransferSigles();
                    tranobj.Id = tOrder.OrderId;
                    tranobj.AdjustNo = tOrder.OrderSn;
                    tranobj.Status = tOrder.Status;
                    tranobj.CustomNo = tranobj.CustomNo;
                    tranobj.AdjustOporate = tranobj.AdjustOporate;
                    tranobj.SalesNo = tranobj.SalesNo;
                    tranobj.SalesLine = tranobj.SalesLine;
                    var trandelist = Context.TTransferBinOrderDetails.AsNoTracking().Where(y => y.OrderId == tOrder.Id);
                    foreach (var tranferBinOrderDetail in trandelist)
                    {
                        tranobj.StoreType = tranferBinOrderDetail.StoreType;
                        tranobj.Factory = tranferBinOrderDetail.Factory;
                        tranobj.StorageNo = tranferBinOrderDetail.FromWhCode;
                        tranobj.StorageArea = tranferBinOrderDetail.StorageArea;
                        tranobj.BinNo = tranferBinOrderDetail.FromLocationCode;
                        tranobj.StockLocation = tranferBinOrderDetail.FromLocationName;
                        tranobj.Quantity = (double)tranferBinOrderDetail.Quantity;
                        tranobj.MaterialNo = tranferBinOrderDetail.MaterialNo;
                        tranobj.MaterialDesc= tranferBinOrderDetail.MaterialName;
                        tranobj.BaseUnit = tranferBinOrderDetail.BaseUnit;
                        tranobj.BatchNo= tranferBinOrderDetail.BatchNo;
                        tranobj.ToBinNo = tranferBinOrderDetail.ToLocationCode;
                        tlis.Add(tranobj);
                    }                                                                
                }
            }
            totalCount = tlis.Count;
            tlis = tlis.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return tlis;
        }

        /// <summary>
        /// 查看移库单的详细信息
        /// </summary>
        /// <param name="Id">移库单id</param>
        /// <returns></returns>
        public TTransferBinOrderDTO SelectTransferBinOrder(int Id)
        {
            var Trans = Context.TTransferBinOrders.FirstOrDefault(t => t.Id == Id);
            if (Trans != null)
            {
                TTransferBinOrderDTO dto = new TTransferBinOrderDTO();
                dto = Mapper.Map<TTransferBinOrderDTO>(Trans);
                dto.OrderDetailList = Context.TTransferBinOrderDetails.Where(t=>t.OrderId==dto.Id).ToList();
                return dto;
            }
            return null;
        }


        /// <summary>
        /// 修改移库单信息
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTransferBinOrder(TTransferBinOrder t)
        {
            try
            {
                t.ModifyDate = DateTime.Now;
                t.ModifyUserId = t.ModifyUserId;
                t.ModifyUserName = t.ModifyUserName;
                Context.TTransferBinOrders.Update(t);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 提交状态
        /// </summary>
        /// <param name="submitTranDTO"></param>
        /// <returns></returns>

        public bool SubmitTranState(SubmitTranDTO submitTranDTO)
        {
            var user = Context.TUsers.Where(u => u.RealName == submitTranDTO.RealName && u.JobNo == submitTranDTO.JoNO).FirstOrDefault();
            if (user != null)
            {
                var tran = Context.TTransferBinOrders.Where(t => t.Id == submitTranDTO.TranId).FirstOrDefault();
                tran.Status = 2;
                if (UpdateTransferBinOrder(tran))
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 删除多条移库明细下物料信息数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>

        public bool DeleteTransferBinOrderDetails(List<int?> ids)
        {
            if (ids == null || ids.Count == 0)
            {
                return false;
            }
            var itemsToRemove = Context.TTransferBinOrderDetails.Where(o => ids.Contains(o.Id)).ToList();; // 找到需要删除的数据
            Context.TTransferBinOrderDetails.RemoveRange(itemsToRemove); // 执行批量删除操作
            int recordsAffected = Context.SaveChanges(); // 保存更改并获取受影响的记录数

            return recordsAffected == ids.Count; // 返回是否成功删除了所有指定的数据

        }
        /// <summary>
        /// 提交移库
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool SubmitTrans(TTransferBinOrderDTO obj)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 移库单导出
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="customerId"></param>
        /// <param name="status"></param>
        /// <param name="warehouseId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TTransferBinOrder> GetExcel(string? ordersn, DateTime? startTime, DateTime? endTime,int? companyId, int? status)
        {
            var list = Context.TTransferBinOrders.AsNoTracking().ToList();
            list = list.OrderByDescending(x => x.CreateDate).ToList();
            // 查找公司
            if (!string.IsNullOrEmpty(ordersn))
            {
                list = list.Where(x => x.OrderSn.Contains(ordersn)).ToList();
            }
            // 查找公司
            if (companyId != 0 && companyId is not null)
            {
                list = list.Where(x => x.CompanyId == companyId).ToList();
            }

            // 查询状态
            if (status is not null)
            {
                list = list.Where(x => x.Status == status).ToList();
            }

            // pda显示收获中和未收货的
            if (status is not null && status == 3)
            {
                list = list.Where(x => x.Status != 2).ToList();
            }

            // 根据时间来筛选
            if (startTime != null && endTime != null)
            {
                list = list.Where(x => x.CreateDate >= startTime && x.CreateDate <= endTime).ToList();
            }

            // pc显示收获中的在上面未收获的在下面
            if (status is not null && status == 4)
            {
                list = list.Where(x => x.Status != 2).OrderByDescending(x => x.Status == 1).ThenByDescending(x => x.Status == 0).ToList();
            }

            return list;
        }

        /// <summary>
        /// 移库任务下传
        /// </summary>
        /// <param name="transferSiglesList"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool TransferTaskDownload(List<TransferSigles> transferSiglesList, out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    #region 改动前
                    //message = "";
                    //var existingOrderIds = Context.TTransferBinOrders.AsNoTracking().Where(x => transferSiglesList.Select(s => s.Id).Distinct().Contains(x.OrderId)).Select(x => x.OrderId).ToList();
                    //foreach (var transfertSigles in transferSiglesList)
                    //{
                    //    if (existingOrderIds.Contains(transfertSigles.Id))
                    //    {
                    //        message += transfertSigles.Id + "存在重复";
                    //        continue;
                    //    }
                    //    var tranferBinOrderDetail = new TTransferBinOrderDetail();              
                    //    var tOrder = new TTransferBinOrder(); 
                    //    tOrder.OrderId = transfertSigles.Id;
                    //    tOrder.OrderSn = transfertSigles.AdjustNo;
                    //    tOrder.Status = 0;
                    //    tOrder.SourceType = 1;
                    //    tOrder.Proirity = 0;
                    //    tOrder.CustomNo = transfertSigles.CustomNo;
                    //    tOrder.AdjustOporate = transfertSigles.AdjustOporate;
                    //    tOrder.SalesNo = transfertSigles.SalesNo;   
                    //    tOrder.SalesLine = transfertSigles.SalesLine;
                    //    tOrder.CreateDate = DateTime.Now;
                    //    Context.TTransferBinOrders.Add(tOrder);
                    //    Context.SaveChanges();
                    //    tranferBinOrderDetail.OrderId = tOrder.Id;
                    //    tranferBinOrderDetail.OrderSn = tOrder.OrderSn;
                    //    tranferBinOrderDetail.Status = 0;
                    //    tranferBinOrderDetail.StoreType = transfertSigles.StoreType;
                    //    tranferBinOrderDetail.Factory = transfertSigles.Factory;   
                    //    tranferBinOrderDetail.FromWhCode = transfertSigles.StorageNo;
                    //    tranferBinOrderDetail.StorageArea = transfertSigles.StorageArea;
                    //    tranferBinOrderDetail.FromLocationCode = transfertSigles.BinNo;
                    //    tranferBinOrderDetail.FromLocationName = transfertSigles.StockLocation;
                    //    tranferBinOrderDetail.Quantity = (int?)transfertSigles.Quantity;
                    //    var materobj = Context.TMaterial.AsNoTracking().FirstOrDefault(x => x.Code == transfertSigles.MaterialNo);
                    //    if (materobj != null)
                    //    {
                    //        tranferBinOrderDetail.MaterialId = materobj.Id;
                    //    }
                    //    else
                    //    {
                    //        TMaterial material = new TMaterial();
                    //        material.Code = transfertSigles.MaterialNo;
                    //        material.Name = transfertSigles.MaterialDesc;
                    //        material.CreateDate = DateTime.Now;
                    //        Context.TMaterial.Add(material);
                    //        Context.SaveChanges();
                    //        tranferBinOrderDetail.MaterialId = material.Id;
                    //    }
                    //    var invenobj = Context.TInventory.AsNoTracking().FirstOrDefault(x => x.MaterialCode == transfertSigles.MaterialNo && x.LocationCode == transfertSigles.BinNo);
                    //    if(invenobj==null)
                    //    {
                    //        message = "库存中未找到此物料："+ transfertSigles.MaterialDesc;
                    //        return false;
                    //    }
                    //    //起始仓位
                    //    var fromcellobj = Context.TCells.AsNoTracking().FirstOrDefault(x => x.Code == transfertSigles.BinNo && x.Status==1 && x.FullStatus==1 && x.BusinessType==0 && x.IsLock==false);
                    //    if (fromcellobj != null) 
                    //    {
                    //        tranferBinOrderDetail.FromLocationId = fromcellobj.Id;
                    //        tranferBinOrderDetail.FromLocationName= fromcellobj.Name;
                    //    }
                    //    else
                    //    {
                    //        message = "仓位不存在或已被占用";
                    //        return false;
                    //    }
                    //    //目标仓位
                    //    var tocellobj = Context.TCells.AsNoTracking().FirstOrDefault(x => x.Code == transfertSigles.ToBinNo && x.Status==1 && x.FullStatus == 0 && x.FullStatus == 0 && x.BusinessType == 0 && x.IsLock == false);
                    //    if (tocellobj != null)
                    //    {
                    //        tranferBinOrderDetail.ToLocationId = tocellobj.Id;
                    //        tranferBinOrderDetail.ToLocationName = tocellobj.Name;
                    //    }
                    //    else
                    //    {
                    //        message = "仓位不存在或已被占用";
                    //        return false;
                    //    }
                    //    tranferBinOrderDetail.MaterialNo = transfertSigles.MaterialNo;
                    //    tranferBinOrderDetail.MaterialName = transfertSigles.MaterialDesc;
                    //    tranferBinOrderDetail.BaseUnit = transfertSigles.BaseUnit;
                    //    tranferBinOrderDetail.BatchNo = transfertSigles.BatchNo;
                    //    tranferBinOrderDetail.SupplierNo = transfertSigles.SupplierNo;
                    //    tranferBinOrderDetail.SupplierName = transfertSigles.SupplierName;
                    //    tranferBinOrderDetail.WbsCode = transfertSigles.WbsCode;
                    //    tranferBinOrderDetail.StoreMark = transfertSigles.StoreMark;
                    //    tranferBinOrderDetail.AdjustQuantity = Convert.ToDecimal(transfertSigles.AdjustQuantity);
                    //    tranferBinOrderDetail.ToLocationCode = transfertSigles.ToBinNo;
                    //    tranferBinOrderDetail.SerialnoParam = transfertSigles.SerialnoParam;
                    //    if(transfertSigles.SerialList.Any())
                    //    {
                    //        foreach (var item in transfertSigles.SerialList)
                    //        {
                    //            tranferBinOrderDetail.MaterialSerialize = item.MaterialSerialize;
                    //        }
                    //    }                      
                    //    Context.TTransferBinOrderDetails.Add(tranferBinOrderDetail);
                    //    existingOrderIds.Add(transfertSigles.Id);
                    //}
                    #endregion
                    message = "";
                    var existingOrderIds = Context.TReceivingBills.AsNoTracking().Where(x => transferSiglesList.Select(s => s.Id).Distinct().Contains(x.OrderId)).Select(x => x.OrderId).ToList();
                    var sexistingOrderIds = Context.TShippingOrderDetails.AsNoTracking().Where(x => transferSiglesList.Select(s => s.Id).Distinct().Contains(x.OrderId)).Select(x => x.OrderId).ToList();
                    var materobj1 = Context.TMaterial.AsNoTracking();
                    var inventoryobj1 = Context.TInventory.AsQueryable();
                    foreach (var shelves in transferSiglesList)
                    {
                        var cellobj = Context.TCells.FirstOrDefault(x => x.Code == shelves.BinNo);
                        //如果等于空代表从平库存到立库
                        if(cellobj==null)
                        {
                            if (existingOrderIds.Contains(shelves.Id))
                            {
                                message += shelves.Id + "存在重复";
                                continue;
                            }
                            var r = new TReceivingBill();
                            r.OrderId = shelves.Id;
                            r.ShelvesNo = shelves.AdjustNo;
                            r.StoLocation = shelves.StockLocation;
                            r.BaseUnit = shelves.BaseUnit;
                            r.StorageArea = shelves.StorageArea;
                            r.BinNo = shelves.BinNo;
                            r.TotalQty = (decimal?)shelves.AdjustQuantity;
                            r.CheckedQty = (decimal?)shelves.Quantity;
                            r.OrderUnit = shelves.BaseUnit;
                            r.CustomerName = shelves.CustomNo;
                            r.BillNo = shelves.AdjustNo;
                            r.SupplierName = shelves.SupplierName;
                            r.Status = 0;
                            r.CreateDate = DateTime.Now;
                            r.NoticeNo = shelves.SalesNo;
                            r.NoticeLineNo = shelves.SalesLine;
                            r.Workers = shelves.AdjustOporate;
                            r.WarehouseId = 2;
                            r.WarehouseName = "中煤科院仓库";
                            r.WarehouseCode = shelves.StorageNo;
                            Context.TReceivingBills.Add(r);
                            Context.SaveChanges();
                            var receivingBillDetail = new TReceivingBillDetail();
                            receivingBillDetail.BillId = r.Id;
                            receivingBillDetail.BillNo = r.BillNo;
                            receivingBillDetail.MaterialCode = shelves.MaterialNo;
                            receivingBillDetail.MaterialName = shelves.MaterialDesc;
                            var materobj = materobj1.AsNoTracking().FirstOrDefault(x => x.Code == shelves.MaterialNo);
                            if (materobj != null)
                            {
                                receivingBillDetail.MaterialId = materobj.Id;
                            }
                            else
                            {
                                TMaterial material = new TMaterial();
                                material.Code = shelves.MaterialNo;
                                material.Name = shelves.MaterialDesc;
                                material.CreateDate = DateTime.Now;
                                material.UnitName = shelves.BaseUnit;
                                material.GrossWeightUnitName = "KG";
                                material.NetWeightUnitName = "KG";
                                Context.TMaterial.Add(material);
                                Context.SaveChanges();
                                receivingBillDetail.MaterialId = material.Id;
                            }
                            if (shelves.SerialList != null)
                            {
                                if (shelves.SerialList.Any())
                                {
                                    foreach (var item in shelves.SerialList)
                                    {
                                        receivingBillDetail.MaterialSerialize += item.MaterialSerialize + ",";
                                    }
                                    receivingBillDetail.MaterialSerialize = receivingBillDetail.MaterialSerialize.TrimEnd(',');
                                }
                            }
                            receivingBillDetail.Qty = (decimal)shelves.AdjustQuantity;
                            receivingBillDetail.ReceivedQty = 0;
                            receivingBillDetail.Status = 0;
                            receivingBillDetail.CreateDate = DateTime.Now;
                            receivingBillDetail.SupplierName = shelves.SupplierName;
                            receivingBillDetail.MaterialDesc = shelves.StoreType;
                            receivingBillDetail.MaterialSerializeBatchNo = shelves.StoreMark;
                            receivingBillDetail.MaterialTypeCode = shelves.SupplierNo;
                            receivingBillDetail.MaterialTypeName = shelves.WbsCode;
                            receivingBillDetail.BatchNo = shelves.BatchNo;
                            receivingBillDetail.ProduceFactory = shelves.Factory;
                            receivingBillDetail.SerialnoParam = shelves.SerialnoParam;
                            Context.TReceivingBillDetails.Add(receivingBillDetail);
                            existingOrderIds.Add(shelves.Id);
                        }
                        else
                        {
                            if (sexistingOrderIds.Contains(shelves.Id))
                            {
                                message += shelves.Id + "存在重复";
                                continue;
                            }
                            var s = new TShippingOrderDetail();
                            var shippinglock = new TShippingLockCell();
                            //出库单明细
                            s.OrderId = shelves.Id;
                            s.OrderSn = shelves.AdjustNo;
                            s.BaseUnit = shelves.BaseUnit;
                            s.DisOrderNo = shelves.SalesNo;
                            s.DisOrderLineNo = shelves.SalesLine;
                            s.SupplierCode = shelves.SupplierNo;
                            s.SupplierName = shelves.SupplierName;
                            s.SubmitUserName = shelves.ToStorageArea;
                            s.CustomNo = shelves.CustomNo;
                            s.ProOrderNo = shelves.Factory;
                            s.WarehouseCode = shelves.StorageNo;
                            s.WarehouseName = "中煤科院仓库";
                            s.WarehouseId = 2;
                            s.PickedQty = (decimal?)shelves.Quantity;
                            s.CreateUserName = shelves.AdjustOporate;                        
                            s.CreateDate = DateTime.Now;
                            s.Erpcode = shelves.WbsCode;
                            s.MaterialCode = shelves.MaterialNo;
                            s.MaterialName = shelves.MaterialDesc;
                            s.Qty = (decimal?)shelves.AdjustQuantity;
                            s.DeptCode = shelves.WbsCode;
                            s.DeptName = shelves.ToBinNo;
                            Context.TShippingOrderDetails.Add(s);
                            Context.SaveChanges();

                            //出库货物单明细                    
                            shippinglock.OrderDetailId = s.Id;
                            shippinglock.OrdeSn = shelves.AdjustNo;
                            if (shelves.SerialList != null)
                            {
                                if (shelves.SerialList.Any())
                                {
                                    foreach (var item in shelves.SerialList)
                                    {
                                        shippinglock.SerialNo += item.MaterialSerialize + ",";
                                    }
                                    shippinglock.SerialNo = shippinglock.SerialNo.TrimEnd(',');
                                }
                            }
                            shippinglock.SerialNumberEnabled = shelves.SerialnoParam;
                            shippinglock.MaterialCode = shelves.MaterialNo;
                            shippinglock.MaterialName = shelves.MaterialDesc;
                            shippinglock.ParentPalletBarcode = shelves.StoreMark;
                            shippinglock.IsPicking = false;
                            shippinglock.StorageArea = shelves.StorageArea;
                            //托盘条码-必要
                            var inventoryobj = inventoryobj1.FirstOrDefault(x => x.MaterialCode == shelves.MaterialNo && x.Status == 1 && x.LocationCode == shelves.BinNo && x.AvailableQty >= (decimal?)shelves.AdjustQuantity);
                            if (inventoryobj != null)
                            {
                                shippinglock.PalletBarcode = inventoryobj.PalletBarcode;
                                shippinglock.InventoryId = inventoryobj.Id;
                                shippinglock.CellId = inventoryobj.LocationId;
                                shippinglock.CellDepthIndex = 0;
                                shippinglock.CellCode = inventoryobj.LocationCode;
                                shippinglock.MaterialId = inventoryobj.MaterialId;
                                shippinglock.InventoryQty = inventoryobj.AvailableQty;
                                inventoryobj.IsLock = true;
                                Context.TInventory.Update(inventoryobj);
                            }
                            else
                            {
                                message += "未在库存中找到此物料：" + shelves.MaterialNo + " 或因库存数量不足！";
                                return false;
                            }
                            shippinglock.CellName = shelves.StockLocation;
                            shippinglock.OutQty = (decimal?)shelves.AdjustQuantity;
                            shippinglock.BatchNo = shelves.BatchNo;
                            shippinglock.StoreType = shelves.StoreType;
                            Context.TShippingLockCells.Add(shippinglock);
                            existingOrderIds.Add(shelves.Id);
                        }
                    }

                    //提交保存
                    Context.SaveChanges();
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    tran.Rollback();
                    return false;
                    throw;
                }
            }
        }

        /// <summary>
        /// 移库单回传
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TransferSigles> BackTransferSigles()
        {
            List<TransferSigles> tlist = new List<TransferSigles>();
            //入库单
            var reolist = Context.TReceivingOrderDetails.AsNoTracking().Where(x => x.Status == 4 && x.OrderSn.Contains("TF"));
            //收货单
            var rlist = Context.TReceivingBills.Where(x => x.Status == 2 && x.OrderId.Length > 0 && x.BillNo.Contains("TF")).AsNoTracking().OrderBy(r => r.CreateDate);
            var list = (from r in reolist
                        join ro in rlist
                        on r.ReceivingBillId equals ro.Id
                        select ro);
            if (rlist.Any())
            {
                foreach (var item in list)
                {
                    TransferSigles sobj = new TransferSigles();
                    sobj.Id = item.OrderId;
                    sobj.AdjustNo = item.ShelvesNo;
                    sobj.StockLocation = item.StoLocation;
                    sobj.BaseUnit = item.BaseUnit;
                    sobj.SupplierName = item.SupplierName;
                    sobj.StorageArea = item.StorageArea;
                    sobj.BinNo = item.BinNo;
                    sobj.ToStorageArea = "002";
                    sobj.CustomNo = item.CustomerName;
                    sobj.SalesNo = item.NoticeNo;
                    sobj.Quantity = (double)item.CheckedQty;
                    sobj.SalesLine = item.NoticeLineNo;
                    sobj.AdjustOporate = item.Workers;
                    sobj.StorageNo = item.WarehouseCode;
                    var locode = reolist.AsNoTracking().FirstOrDefault(x => x.ReceivingBillId == item.Id);
                    sobj.ToBinNo = locode.LocationCode;
                    var revbilldelist = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == item.Id);
                    if (revbilldelist.Any())
                    {
                        foreach (var item2 in revbilldelist)
                        {
                            sobj.MaterialNo = item2.MaterialCode;
                            sobj.MaterialDesc = item2.MaterialName;
                            sobj.SupplierName = item2.SupplierName;
                            sobj.SupplierNo = item2.MaterialTypeCode;
                            sobj.BatchNo = item2.BatchNo;
                            sobj.Factory = item2.ProduceFactory;
                            sobj.SerialnoParam = item2.SerialnoParam;
                            sobj.StoreType = item2.MaterialDesc;
                            sobj.StoreMark = item2.MaterialSerializeBatchNo;
                            sobj.WbsCode = item2.MaterialTypeName;
                            sobj.AdjustQuantity = (double)item2.Qty;
                            if (!string.IsNullOrEmpty(item2.MaterialSerialize))
                            {
                                item2.MaterialSerialize = item2.MaterialSerialize.TrimEnd(',');
                                foreach (var item3 in item2.MaterialSerialize.Split(','))
                                {
                                    SerialLists bserobj = new SerialLists();
                                    bserobj.MaterialSerialize = item3;
                                    sobj.SerialList.Add(bserobj); 
                                }
                            }
                            else
                            {
                                SerialLists bserobj = new SerialLists();
                                bserobj.MaterialSerialize = item2.MaterialSerialize;
                                sobj.SerialList.Add(bserobj);
                            }

                        }
                    }
                    tlist.Add(sobj);                  
                }
            }
            //出库单
            var sorderlist = Context.TShippingOrderDetails.AsNoTracking().Where(x => x.Status == 4 && x.OrderSn.Contains("TF") && x.OrderId.Length > 0).OrderBy(x => x.CreateDate);
            if (sorderlist.Any())
            {
                foreach (var item in sorderlist)
                {
                    TransferSigles pobj = new TransferSigles();
                    //出库单明细
                    pobj.Id = item.OrderId;
                    pobj.AdjustNo = item.OrderSn;
                    pobj.BaseUnit = item.BaseUnit;
                    pobj.SalesNo = item.DisOrderNo;
                    pobj.SalesLine = item.DisOrderLineNo;
                    pobj.SupplierNo = item.SupplierCode;
                    pobj.SupplierName = item.SupplierName;
                    pobj.CustomNo = item.CustomNo;
                    pobj.ToStorageArea = item.SubmitUserName;
                    pobj.Factory = item.ProOrderNo;                  
                    pobj.WbsCode = item.DeptCode;
                    pobj.ToBinNo = item.DeptName;
                    pobj.StorageNo = item.WarehouseCode;
                    pobj.AdjustOporate = item.CreateUserName;
                    pobj.Quantity = (double)item.PickedQty;
                    //出库单明细
                    var sloclist = Context.TShippingLockCells.AsNoTracking().Where(x => x.OrderDetailId == item.Id);
                    if (sloclist.Any())
                    {
                        foreach (var item2 in sloclist)
                        {
                            //出库货物单明细
                            pobj.AdjustNo = item2.OrdeSn;
                            pobj.SerialnoParam = item2.SerialNumberEnabled;
                            pobj.MaterialNo = item2.MaterialCode;
                            pobj.MaterialDesc = item2.MaterialName;
                            pobj.StoreMark = item2.ParentPalletBarcode;
                            pobj.StorageArea = item2.StorageArea;
                            pobj.BinNo = item2.CellCode;
                            pobj.StockLocation = item2.CellName;
                            //缺少序列号启用标识
                            if (!string.IsNullOrEmpty(item2.SerialNo))
                            {
                                item2.SerialNo = item2.SerialNo.TrimEnd(',');
                                foreach (var item3 in item2.SerialNo.Split(','))
                                {
                                    SerialLists bserobj = new SerialLists();
                                    bserobj.MaterialSerialize = item3;
                                    pobj.SerialList.Add(bserobj);
                                }
                            }
                            else
                            {
                                SerialLists bserobj = new SerialLists();
                                bserobj.MaterialSerialize = item2.SerialNo;
                                pobj.SerialList.Add(bserobj);
                            }                          
                            pobj.AdjustQuantity = (double)item2.OutQty;
                            pobj.BatchNo = item2.BatchNo;
                            pobj.StoreType = item2.StoreType;
                            
                        }
                    }
                    tlist.Add(pobj);
                }
            }
            return tlist;
        }

        /// <summary>
        /// 移库单回传修改状态
        /// </summary>
        /// <param name="ridlist"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdBackTranState(List<string> ridlist)
        {
            foreach (var rid2 in ridlist)
            {
                var robj = Context.TTransferBinOrders.AsNoTracking().FirstOrDefault(x => x.OrderId == rid2);
                if (robj != null)
                {
                    robj.Status = 5;
                    Context.TTransferBinOrders.Update(robj);
                }
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 夜间移库数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TransferNight> BackTransferNight()
        {
            List<string> invcellcode = new List<string>();
            invcellcode = Context.TInventory.Where(x=>x.Status==1 && x.IsLock==false).Select(x => x.LocationCode).Distinct().OrderBy(x=>x).ToList();
            int value = 0;
            int value2 = 0;
            int value3 = 0;
            int value4 = 0;
            string tobino = "";
            using (var trans = Context.Database.BeginTransaction())
            {
                //仓位
                foreach (var item in invcellcode)
                {
                    MatchCollection match = Regex.Matches(item, @"\d+");
                    //巷道
                    value = Convert.ToInt32(match[0].Value);
                    //排
                    value2 = Convert.ToInt32(match[1].Value);
                    //列
                    value3 = Convert.ToInt32(match[2].Value);
                    //层
                    value4 = Convert.ToInt32(match[3].Value);
                    if(value4==1)
                    {
                        var tcellobj = Context.TCells.Where(x => x.IsMaxDepth == true && x.RoutewayId == value && x.LineNo == value2 && x.Status == 1 && x.LayerNo == 1 && x.ColumnNo < value3 && x.FullStatus == 0 && x.IsLock == false && x.BusinessType == 0)
                        .OrderByDescending(c => c.DepthIndex)
                                  .ThenBy(c => c.LayerNo)
                                  .ThenBy(c => c.ColumnNo)
                                  .ThenBy(c => c.LineNo).FirstOrDefault();
                        if (tcellobj == null)
                        {
                            continue;
                        }
                        tcellobj.FullStatus = 1;
                        tcellobj.ModifyDate = DateTime.Now;
                        tobino = tcellobj.Code;
                    }
                    else
                    {
                        var tcellobj = Context.TCells.Where(x => x.IsMaxDepth == true && x.RoutewayId == value && x.LineNo == value2 && x.LayerNo< value4 && x.Status == 1 && x.FullStatus == 0 && x.IsLock == false && x.BusinessType == 0)
                        .OrderByDescending(c => c.DepthIndex)
                                  .ThenBy(c => c.LayerNo)
                                  .ThenBy(c => c.ColumnNo)
                                  .ThenBy(c => c.LineNo).FirstOrDefault();
                        if (tcellobj == null)
                        {
                            var tcellobj2 = Context.TCells.Where(x => x.IsMaxDepth == true && x.RoutewayId == value && x.LineNo == value2 && x.LayerNo == value4 && x.ColumnNo<value3 && x.Status == 1 && x.FullStatus == 0 && x.IsLock == false && x.BusinessType == 0)
                        .OrderByDescending(c => c.DepthIndex)
                                  .ThenBy(c => c.LayerNo)
                                  .ThenBy(c => c.ColumnNo)
                                  .ThenBy(c => c.LineNo).FirstOrDefault();
                            if(tcellobj2==null)
                            {
                                continue;
                            }
                            tobino = tcellobj2.Code;
                            tcellobj2.FullStatus = 1;
                            tcellobj2.ModifyDate = DateTime.Now;
                        }
                        else
                        {
                            tobino = tcellobj.Code;
                            tcellobj.FullStatus = 1;
                            tcellobj.ModifyDate = DateTime.Now;
                        }                   
                    }
                    
                    TTransferBinOrder transferBinOrder = new TTransferBinOrder();
                    transferBinOrder.OrderSn = "YJ" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    transferBinOrder.SourceType = 1;
                    transferBinOrder.CreateDate = DateTime.Now;
                    transferBinOrder.CreateUserName = "系统";

                    Context.TTransferBinOrders.Add(transferBinOrder);

                    TTransferBinOrderDetail transferBinOrderDetail = new TTransferBinOrderDetail();
                    transferBinOrderDetail.OrderId = transferBinOrder.Id;
                    transferBinOrderDetail.FromLocationCode = item;
                    transferBinOrderDetail.ToLocationCode = tobino;
                    transferBinOrderDetail.Status = 0;
                    Context.TTransferBinOrderDetails.Add(transferBinOrderDetail);
                    Context.SaveChanges();
                }


                List<TransferNight> transferNights = new List<TransferNight>();
                var list = Context.TTransferBinOrderDetails.Where(x => x.Status == 0);
                if (list.Any())
                {
                    string? pallbarcode = Context.TInventory.FirstOrDefault(x => x.LocationCode == list.First().FromLocationCode)?.PalletBarcode;
                    transferNights = list.Select(x => new TransferNight
                    {
                        Id = x.OrderId,
                        LocationCode = x.FromLocationCode,
                        TargetLocationCode = x.ToLocationCode,
                        PalletBarcode = pallbarcode,
                    }).ToList();
                }
                return transferNights;
            }     
        }
    }
}

 